from datetime import datetime
from typing import Optional, List
from pydantic import BaseModel, Field, validator, ConfigDict
from enum import Enum


class ScoreLevelEnum(int, Enum):
    """
    评分等级枚举
    定义1-10分评分等级（支持自定义扩展）
    """
    LEVEL_1 = 1   # 极差
    LEVEL_2 = 2   # 不足
    LEVEL_3 = 3   # 合格
    LEVEL_4 = 4   # 优秀
    LEVEL_5 = 5   # 卓越
    LEVEL_6 = 6   # 自定义等级6
    LEVEL_7 = 7   # 自定义等级7
    LEVEL_8 = 8   # 自定义等级8
    LEVEL_9 = 9   # 自定义等级9
    LEVEL_10 = 10 # 自定义等级10


class DimensionScoreRuleBase(BaseModel):
    """
    维度评分规则基础模型
    包含评分规则的基本信息字段
    """
    dimension_id: int = Field(..., description="关联评分维度ID", gt=0)
    score_level: int = Field(..., description="评分等级（1分最低，支持自定义扩展）", ge=1, le=10)
    level_desc: str = Field(..., description="等级描述", max_length=50)
    judge_criteria: str = Field(..., description="具体评判标准", min_length=1)
    
    @validator('level_desc')
    def validate_level_desc(cls, v):
        """
        验证等级描述
        确保等级描述不为空且长度合适
        """
        if not v or not v.strip():
            raise ValueError('等级描述不能为空')
        if len(v.strip()) > 50:
            raise ValueError('等级描述长度不能超过50个字符')
        return v.strip()
    
    @validator('judge_criteria')
    def validate_judge_criteria(cls, v):
        """
        验证评判标准
        确保评判标准不为空
        """
        if not v or not v.strip():
            raise ValueError('评判标准不能为空')
        return v.strip()


class DimensionScoreRuleCreate(DimensionScoreRuleBase):
    """
    创建维度评分规则模型
    用于创建新规则时的数据验证
    """
    pass


class DimensionScoreRuleUpdate(BaseModel):
    """
    更新维度评分规则模型
    用于更新规则时的数据验证，所有字段都是可选的
    """
    dimension_id: Optional[int] = Field(None, description="关联评分维度ID", gt=0)
    score_level: Optional[int] = Field(None, description="评分等级", ge=1, le=10)
    level_desc: Optional[str] = Field(None, description="等级描述", max_length=50)
    judge_criteria: Optional[str] = Field(None, description="具体评判标准")
    
    @validator('level_desc')
    def validate_level_desc(cls, v):
        """
        验证等级描述
        """
        if v is not None:
            if not v or not v.strip():
                raise ValueError('等级描述不能为空')
            if len(v.strip()) > 50:
                raise ValueError('等级描述长度不能超过50个字符')
            return v.strip()
        return v
    
    @validator('judge_criteria')
    def validate_judge_criteria(cls, v):
        """
        验证评判标准
        """
        if v is not None:
            if not v or not v.strip():
                raise ValueError('评判标准不能为空')
            return v.strip()
        return v


class DimensionScoreRuleResponse(DimensionScoreRuleBase):
    """
    维度评分规则响应模型
    用于API响应时返回规则信息
    """
    id: int = Field(..., description="规则唯一ID")
    create_time: datetime = Field(..., description="规则创建时间")

    model_config = ConfigDict(from_attributes=True)


class DimensionScoreRuleListResponse(BaseModel):
    """
    维度评分规则列表响应模型
    用于分页查询时返回规则列表
    """
    total: int = Field(..., description="总数量")
    items: List[DimensionScoreRuleResponse] = Field(..., description="规则列表")


class RuleQuery(BaseModel):
    """
    规则查询模型
    用于查询规则时的参数验证
    """
    page: int = Field(1, description="页码", ge=1)
    size: int = Field(10, description="每页数量", ge=1, le=100)
    keyword: Optional[str] = Field(None, description="搜索关键词")
    dimension_id: Optional[int] = Field(None, description="按维度ID筛选", gt=0)
    score_level: Optional[int] = Field(None, description="按评分等级筛选", ge=1, le=10)


class BatchCreateRulesRequest(BaseModel):
    """
    批量创建规则请求模型
    用于一次性为某个维度创建所有等级的规则
    """
    dimension_id: int = Field(..., description="维度ID", gt=0)
    rules: List[dict] = Field(..., description="规则列表，格式：[{\"score_level\": 1, \"level_desc\": \"极差\", \"judge_criteria\": \"...\"}]")

    model_config = ConfigDict(json_schema_extra={
        "example": {
            "dimension_id": 1,
            "rules": [
                {"score_level": 1, "level_desc": "极差", "judge_criteria": "完全不符合要求，存在严重问题"},
                {"score_level": 2, "level_desc": "不足", "judge_criteria": "基本不符合要求，存在较多问题"},
                {"score_level": 3, "level_desc": "合格", "judge_criteria": "基本符合要求，达到及格水平"},
                {"score_level": 4, "level_desc": "优秀", "judge_criteria": "符合要求，表现良好"},
                {"score_level": 5, "level_desc": "卓越", "judge_criteria": "完全符合要求，表现出色"},
                {"score_level": 6, "level_desc": "自定义6级", "judge_criteria": "自定义评判标准6"},
                {"score_level": 7, "level_desc": "自定义7级", "judge_criteria": "自定义评判标准7"}
            ]
        }
    })